<template>
  <div class="container">
    <!-- 地图容器 -->
    <div id="map" v-if="showMap" :style="{ cursor: cursor }" style="height: 106%"></div>
    
    <!-- 自定义弹出框 -->
    <!-- <div class="custom-popover-container" ref="popoverContainer">
      <button class="popover-toggle" @click.stop="togglePopover">
        <img width="50" :src="titleImg" alt="" />
      </button>
      
      <div v-show="isPopoverVisible" class="custom-popover" ref="popover">
        <div class="map-controls">
          <div class="control-group">
            <div class="image-options">
              <div class="image-option" v-for="(option, index) in imageOptions" :key="index"
                @click="changeImageType(option.value); hidePopover()">
                <img :src="option.icon" alt="">
                <span>{{ option.label }}</span>
              </div>
            </div>
          </div>
 
          <div class="control-group">
            <div class="terrain-options">
              <div class="terrain-option" v-for="(option, index) in terrainOptions" :key="index"
                @click="changeTerrainType(option.value); hidePopover()">
                <img :src="option.icon" alt="">
                <span>{{ option.label }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div> -->

  </div>
</template>

<script>
import { initMap, getBaseMap, getViewMode } from "@utils/map/map";
import Member from "@utils/map/members";
import FitBounds from "@utils/map/fitBounds";
import { setTheme } from "@theme/theme";
import { reqOrg, reqSpaceByOrgId } from "@api/apiDatav.js";
import { mapState, mapMutations } from "vuex";

export default {
  components: {},
  data() {
    return {
      cursor: "grab",
      map: null,
      member: null,
      fitBounds: null,
      mapTimer: null,
      showMap: true,
      radio1: '地图',
      radio2: '2D',
       isPopoverVisible: false,
      imageOptions: [
        { label: '正常影像', value: '地图', icon: require("@assets/images/datav/normal.jpg") },
        { label: '卫星影像', value: '卫星', icon: require("@assets/images/datav/tdt_img.jpg") },
      ],
      terrainOptions: [
        { label: '2D', value: '2D', icon: require("@assets/images/datav/2D.jpg") },
        { label: '3D', value: '3D', icon: require("@assets/images/datav/3D.jpg") }
      ],
      titleImg: require("@assets/images/datav/normal.jpg"),
    };
  },
  computed: {
    ...mapState(["user", "datav", "spacesManage"]),
    cursorGrab() {
      return this.datav.cursor;
    },
  },
  watch: {
    cursorGrab(val) {
      this.cursor = val;
    },
  },
   mounted() {
    document.addEventListener('click', this.handleClickOutside);
  },
  beforeDestroy() {
    document.removeEventListener('click', this.handleClickOutside);
    this.showMap = false;
    clearTimeout(this.mapTimer);
  },
  methods: {
    ...mapMutations(["savebuildingsSum"]),
    togglePopover(event) {
      // 阻止事件冒泡，避免立即触发handleClickOutside
      event.stopPropagation();
      this.isPopoverVisible = !this.isPopoverVisible;
      // 如果弹出框刚刚显示，添加全局点击监听
      if (this.isPopoverVisible) {
        document.addEventListener('click', this.handleClickOutside);
      } else {
        document.removeEventListener('click', this.handleClickOutside);
      }
    },
    hidePopover() {
      this.isPopoverVisible = false;
      document.removeEventListener('click', this.handleClickOutside);
    },
    handleClickOutside(event) {
      const popoverContainer = this.$refs.popoverContainer;
      const popover = this.$refs.popover;
      // 检查点击是否在弹出框容器内部或弹出框本身
      if (popoverContainer && !popoverContainer.contains(event.target) && 
          popover && !popover.contains(event.target)) {
        this.hidePopover();
      }
    },
    changeImageType(e){
      console.log(e);
       if (e == '地图') {
        getBaseMap('vector')
      } else if (e == '卫星') {
        getBaseMap('satellite')
      }
    },
    changeTerrainType(e){
  if (e == '2D') {
        getViewMode('2D')
      } else if (e == '3D') {
        getViewMode('3D')
      }
    },
  
  
    init() {
      setTheme("dark"); // 初始化未默认主题
      // if (screenfull.isEnabled) {
      //   screenfull.on("change", this.change);
      // }
    },
    // 单位列表 确认按钮
    async getOrg2(list) {
      if (list.length == 0) {
        this.member.closeAll();
        return;
      }
      this.member.changePjt(list, true);
      this.fitBounds.setBoundaryInMap(list, true); // 移动到指定的范围
    },
    // 单位列表
    async getOrg(init = false) {
      let res = await reqOrg({
        tenantId: this.user.tenantId,
        userId: this.user.userId,
        roleName: this.user.roleName,
        regionCode: "",
        orgId: this.spacesManage.organizationInfo.orgId,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      // console.log(res.data.row, "地图列表",this.spacesManage.organizationInfo.orgId);
      if (res.data.row.length == 0) {
        if (this.user.tenantId == "1821064521231855617") {
          // 进入大屏默认安徽省地图 销售需求
          this.fitBounds.setBoundaryInMap(
            [{ lat: "31.86119", lng: "117.283042" }],
            true,
            7.8,
          ); // 移动到指定的范围
        } else {
          this.member.closeAll();
        }
        return;
      }
      if (init) {
        this.member = new Member(
          this.map,
          res.data.row,
          true,
          (geometry, flag) => {
            if (flag) {
              // 单位点击
              this.$emit("showUnit", geometry);
            } else {
              // 建筑物点击
              this.fitBounds.setBoundaryInMap([geometry], true, 19); // 移动到指定的范围
            }
          }
        );
      } else {
        this.member.changePjt(res.data.row, true);
      }
      if (this.user.tenantId == "1821064521231855617") {
        // 进入大屏默认安徽省地图 销售需求
        this.fitBounds.setBoundaryInMap(
          [{ lat: "31.86119", lng: "117.283042" }],
          true,
          7.8,
        ); // 移动到指定的范围
      } else {
        this.fitBounds.setBoundaryInMap(res.data.row, true); // 移动到指定的范围
      }
    },

    // 建筑物列表
    async getSpaceByOrgId(init = false, flag = false) {
      if (this.member != null) {
        this.member.closeAll();
      }
      let res = await reqSpaceByOrgId(this.datav.orgarr.id);
      // console.log(res.data.row, "建筑物");
      this.fitBounds.setBoundaryInMap([this.datav.orgarr], true, 15); // 根据单位地址 移动到单位指定的范围
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.savebuildingsSum(res.data.row.length); //建筑物数量
      // if (res.data.row.length == 0 && this.member != null) {
      //   this.member.closeAll();
      //   return;
      // }
      if (init) {
        this.member = new Member(
          this.map,
          res.data.row,
          false,
          (geometry, flag) => {
            if (!flag) {
              // 建筑物图标点击
              this.fitBounds.setBoundaryInMap([geometry], true, 19); // 移动到指定的范围
            }
          }
        );
      } else {
        if (flag) return; //切换相同的单位不执行
        this.member.changePjt(res.data.row);
      }
      // console.log(this.datav.orgarr);
    },
    //初始化
    getinitMap(e = false) {
      // this.mapTimer && clearTimeout(this.mapTimer);
      this.map = initMap("map"); //初始化
      this.fitBounds = new FitBounds(this.map);
      // console.log(e, "e");
      if (e) {
        this.getOrg(true); // 单位列表
      } else {
        this.getSpaceByOrgId(true); // 建筑物列表
      }
    },
  },
  created() {
    this.init();
  },
  mounted() {
    // 需要有单位详情，不能单独走这下面代码
    // this.mapTimer && clearTimeout(this.mapTimer);
    // this.mapTimer = setTimeout(() => {
    //   this.map = initMap("map"); //初始化
    //   // this.fitBounds = new FitBounds(this.map);
    //   // this.$nextTick(()=>{
    //     this.getinitMap()//地图初始化
    //   // })
    // }, 500);
  },
  beforeDestroy() {
    // 确保移除事件监听
    document.removeEventListener('click', this.handleClickOutside);
    this.showMap = false;
    clearTimeout(this.mapTimer);
  }
};
</script>

<style lang="less" scoped>
.marginLeft (@px, @attr: margin-left) {
  @vw: (@px / 1920) * 100;
  @{attr}: ~"@{vw}vw";
}
/* 原有样式保持不变 */
.container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  box-sizing: border-box;
  position: relative;
}
 
.custom-popover-container {
  position: absolute;
  .marginLeft(1400);  
  bottom: 230px;
  z-index: 10000;
  
  .popover-toggle {
    background: none;
    border: none;
    cursor: pointer;
    padding: 0;
    
    img {
      display: block;
    }
  }
}
 
.custom-popover {
  position: absolute;
  bottom: 100%;
  left: 50%;
  transform: translateX(-50%);
  margin-bottom: 10px;
  background-color: rgba(0, 0, 0, 0.85);
  border-radius: 4px;
  padding: 10px;
  min-width: 200px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3);
  
  &::after {
    content: '';
    position: absolute;
    top: 100%;
    left: 50%;
    transform: translateX(-50%);
    border-width: 8px;
    border-style: solid;
    border-color: rgba(0, 0, 0, 0.85) transparent transparent transparent;
  }
}
 
.map-controls {
  color: white;
}
 
.control-group {
  margin-bottom: 15px;
  
  &:last-child {
    margin-bottom: 0;
  }
}
 
.image-options,
.terrain-options {
  display: flex;
  flex-wrap: wrap;
}
 
.image-option,
.terrain-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 5px;
  cursor: pointer;
  transition: opacity 0.2s;
  
  &:hover {
    opacity: 0.8;
  }
  
  img {
    width: 60px;
    height: 60px;
    margin-bottom: 5px;
    object-fit: cover;
  }
  
  span {
    font-size: 12px;
  }
}
</style>
